package com.atguigu.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.MyBaseContext;
import com.atguigu.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    //用于进行URI的匹配
    private static AntPathMatcher PATH_MATCH = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("本次请求的URI为：{}", requestURI);
        //2.判断本次请求是否需要处理
        String[] passStrings = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/dish/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"};
        //3.如果不需要处理，直接放行
        if (match(passStrings, requestURI)) {
            log.info("本次登录不需要处理，直接放行");
            filterChain.doFilter(request, response);
            return;
        }
        //4-1.判读PC端登陆状态，如果已登录，则直接放行
        Object employee_id = request.getSession().getAttribute("employee_id");
        if (employee_id != null) {
            log.info("用户已登录，用户ID={}", employee_id);
            MyBaseContext.set(employee_id);
            filterChain.doFilter(request, response);
            return;
        }
        //4-2判读移动端登陆状态，如果已登录，则直接放行
        Object user_id = request.getSession().getAttribute("user");
        if (user_id != null) {
            log.info("用户已登录，用户ID={}", user_id);
            MyBaseContext.set(user_id);
            filterChain.doFilter(request, response);
            return;
        }
        //5.如果未登录，则返回未登录结果(通过输出流的方式）
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    //判断本次请求是否需要处理
    public boolean match(String[] passStrings, String requestURI) {
        for (String passString : passStrings) {
            boolean match = PATH_MATCH.match(passString, requestURI);
            //
            if (match) {
                return true;
            }
        }
        return false;
    }
}
